#include "simserver.h"
#define SERVER_PORT 1111

SimServer::SimServer(QObject *parent) : QObject(parent)
{
    skt = NULL;
    server = new QTcpServer(this);
    server->listen(QHostAddress::LocalHost, SERVER_PORT);
    connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
}

int SimServer::writeData(QString _data)
{
    if(skt == NULL)
        return -1;

    return skt->write(_data.toLocal8Bit());
}

SimServer::~SimServer()
{

}

void SimServer::newConnection()
{
    if(server->hasPendingConnections())
    {
        if(skt != NULL)
            skt->deleteLater();

        skt = server->nextPendingConnection();
        emit newState(true);
        connect(skt, SIGNAL(readyRead()), this, SLOT(readData()));
        connect(skt, SIGNAL(disconnected()), this, SLOT(disConnect()));
        connect(skt, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(connectStateChanged(QAbstractSocket::SocketState)));
    }
}

void SimServer::disConnect()
{
    qDebug()<<"disConnect";
    emit newState(false);
}

void SimServer::connectStateChanged(QAbstractSocket::SocketState state)
{
    if(state == QAbstractSocket::UnconnectedState)
    {
        qDebug()<<"UnconnectedState";
    }
}

void SimServer::readData()
{
    QByteArray qba = skt->readAll();
    emit newData(QString(qba));
}
